import { extend, isObject } from "../share"
import { track, trigger } from "./effect"
import { reactive, ReactiveFlags, readonly } from './reactive'
const get = createGetter()
const set = createSetter()
const readonlyGet = createGetter(true)
const shallowReadonlyGet = createGetter(true, true)

function createGetter(isReadonly = false, isShallow = false) {
  return function get(target, key) {
    const res = Reflect.get(target, key)
    if(key === ReactiveFlags.IS_REACTIVE) {
      return !isReadonly
    } else if(key === ReactiveFlags.IS_READONLY) {
      return isReadonly
    }
    //依赖收集
    if(!isReadonly) {
      track(target,key)
    } 
    if(isShallow) {
      return res
    }
    if(isObject(res)) {
      return isReadonly ? readonly(res) : reactive(res)
    }
    return res
  }
}

function createSetter() {
  return function set(target, key, value) {
    const res = Reflect.set(target, key, value)
    //触发依赖
    trigger(target,key)
    return res
  }
}

export const mutableHandlers = {
  get,
  set,
}

export const readonlyHandlers = {
  get: readonlyGet,
  set (target, key) {
    console.warn(`${key} no set`)
    return true
  }
}

export const shallowReadonlyHandlers = extend({},readonlyHandlers, {
  get: shallowReadonlyGet
})